package me
import grails.converters.JSON
import com.mysql.cj.jdbc.MysqlConnectionPoolDataSource
import groovy.sql.Sql
import groovy.json.*
import groovy.json.JsonSlurper
import grails.plugins.rest.client.RestBuilder
import oracle.jdbc.pool.OracleDataSource;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
import net.sourceforge.jtds.jdbcx.JtdsDataSource;
class RemoteadapterController {

	def dataSource

    def index() { 

    	
    }

  	def store() {
		def sql = new Sql(dataSource)
   		def results = [:]	  
    	def rows = sql.rows("select * from remote_adapter")
    	results.total = rows.size()
    	results = [success:true,total:rows.size(),results:rows]


      /*def rest = new RestBuilder()
      def resp = rest.get("http://120.55.58.28/rfidApi/carQueue")
      def json = resp.json
      println json*/

    	render results as JSON
  	}


  	def delete() {
  		def data = RemoteAdapter.findById(params.id)
  		data.delete(flush: true) 
  		def results = [success:true]
    	render results as JSON
  	}

    def testsource() {
 		def results = [success:true,message:"success"]
		def sql = new Sql(dataSource)
		def url = params.url
		Binding binding = new Binding();
		if (params.id!=null && params.id!="") {
			sql.rows("select * from chart_param where chart_id = ?",params.id as Integer).each{
				url = url.replace("\${"+it.param_name+"}","${it.param_default}")
				binding.setVariable(it.param_name, it.param_default);
			}
		}
		binding.setVariable("url", url);
		
		try {
			GroovyShell shell = new GroovyShell(binding);
			Object value = shell.evaluate(params.adapterSource);
			println value
			results = [success:true,message:value]
		} catch (e) {
			println e
			results = [success:false,message:e.message]
		}
		
		
    	render results as JSON 
  	}

  	def save() {
  		def sql = new Sql(dataSource)
   		def resuls = [code:0,message:'success']
   		def adapterId = params.adapterId

   		if (adapterId==null || adapterId=="") {
   			def data = new RemoteAdapter(adapterName: params.adapterName, adapterSource: params.adapterSource)
			data.save(failOnError: true)
   		} else {
   			def data = RemoteAdapter.findById(adapterId)
   			data.adapterName = params.adapterName    
   			data.adapterSource = params.adapterSource     
   			try {
  			    data.save(failOnError: true,flush: true) 
  			}
  			catch (e) {
  			    println e
  			}
   		}
    	
    	render resuls as JSON
  	}

}
